@file:Suppress("NOTHING_TO_INLINE")

package com.hzw.core.resources

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.TypedValue
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import com.hzw.core.ctx.appCtx

private val tmpValue by lazy { TypedValue() }

fun Context.drawable(@DrawableRes drawableResId: Int): Drawable? {
    @Suppress("CascadeIf")
    return if (Build.VERSION.SDK_INT >= 21) getDrawable(drawableResId)
    else if (Build.VERSION.SDK_INT >= 16) {
        @Suppress("DEPRECATION")
        resources.getDrawable(drawableResId)
    } else {
        val resolvedId = synchronized(tmpValue) {
            resources.getValue(drawableResId, tmpValue, true)
            tmpValue.resourceId
        }
        @Suppress("DEPRECATION")
        resources.getDrawable(resolvedId)
    }
}

inline fun Fragment.drawable(@DrawableRes drawableResId: Int) = context!!.drawable(drawableResId)
inline fun View.drawable(@DrawableRes drawableResId: Int) = context.drawable(drawableResId)
inline fun appDrawable(@DrawableRes drawableResId: Int) = appCtx.drawable(drawableResId)


fun Context.styledDrawable(@AttrRes attr: Int): Drawable? = withStyledAttributes(attr) { getDrawable(it) }
inline fun Fragment.styledDrawable(@AttrRes attr: Int) = context!!.styledDrawable(attr)
inline fun View.styledDrawable(@AttrRes attr: Int) = context.styledDrawable(attr)
inline fun appStyledDrawable(@AttrRes attr: Int) = appCtx.styledDrawable(attr)